package com.cjkj.system.controller;

import com.cjkj.common.core.web.controller.BaseController;
import com.cjkj.common.core.web.domain.AjaxResult;
import com.cjkj.common.log.annotation.Log;
import com.cjkj.common.log.enums.BusinessType;
import com.cjkj.common.security.service.TokenService;
import com.cjkj.common.security.utils.SecurityUtils;
import com.cjkj.system.api.domain.THospitalUser;
import com.cjkj.system.api.model.LoginUser;
import com.cjkj.system.service.ITHospitalUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 个人信息 业务处理
 */
@RestController
@RequestMapping("/user/profile")
public class HospitalUserProfileController extends BaseController
{
    @Resource
    private ITHospitalUserService userService;
    
    @Resource
    private TokenService tokenService;
    
    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile()
    {
        return AjaxResult.success(userService.selectTHospitalUserByUserId(SecurityUtils.getUserId()));
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody THospitalUser user)
    {
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword)
    {
        String username = SecurityUtils.getUsername();
        THospitalUser user = userService.getUserByUserName(username);
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return error("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(username, newPassword) > 0)
        {
            // 更新缓存用户密码
            LoginUser loginUser = SecurityUtils.getLoginUser();
            loginUser.getSysUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }
}
